package com.litong.spring.mvc.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SpringMvcHandlerInterceptor implements HandlerInterceptor {

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    log.info("SpringMvcHandlerInterceptor.preHandle()");
    String json = buildJson();
    response.setContentType(MediaType.APPLICATION_JSON_VALUE);
    response.getWriter().println(json);
    return false;
  }

  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
      ModelAndView modelAndView) throws Exception {
    log.info("SpringMvcHandlerInterceptor.postHandle()");
  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
      throws Exception {
    log.info("SpringMvcHandlerInterceptor.afterCompletion()");
  }

  private String buildJson() {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("code", "-1");
    jsonObject.put("msg", "sorry");
    jsonObject.put("master", "litongjava@qq.com");
    return jsonObject.toJSONString();
  }
}
